<template>
  <div class="layout-container">
    <div class="layout-container-form">
      <div class="layout-container-opt" style="">
        <el-button
          v-if="adminInfo.admin_type < 2 || (adminInfo.admin_type === 2 && adminInfo.action_permissions && adminInfo.action_permissions.includes('3'))"
          :type="'primary'"
          :loading="exportBatchLoading" @click="handleBatchImport">
          上传用户表奖励
        </el-button>
        <el-button
          v-if="adminInfo.admin_type < 2 || (adminInfo.admin_type === 2 && adminInfo.action_permissions && adminInfo.action_permissions.includes('3'))"
          :type=" 'primary'" :disabled="!selcetRow.Id"
          :loading="exportBatchLoading" @click="exportExcelFun">
          导出选择奖励表
        </el-button>
        <el-button
          v-if="adminInfo.admin_type < 2 || (adminInfo.admin_type === 2 && adminInfo.action_permissions && adminInfo.action_permissions.includes('3'))"
          :type=" 'primary'" :disabled="!selcetRow.Id"
          :loading="exportBatchLoading" @click="handleOpt(0)">
          删除选择数据
        </el-button>
      </div>
      <div class="layout-container-opt-right">
        <el-button
          v-if="adminInfo.admin_type < 2 || (adminInfo.admin_type === 2 && adminInfo.action_permissions && adminInfo.action_permissions.includes('3'))"
          :type="'primary'" :disabled="selcetRow.user_status == 1"
          :loading="exportBatchLoading" @click="handleOpt(1)">
          发放用户工资
        </el-button>
        <el-button
          v-if="adminInfo.admin_type < 2 || (adminInfo.admin_type === 2 && adminInfo.action_permissions && adminInfo.action_permissions.includes('3'))"
          :type=" 'primary'" :disabled="selcetRow.team_status == 1"
          :loading="exportBatchLoading" @click="handleOpt(2)">
          发放团长工资
        </el-button>
        <el-button
          v-if="adminInfo.admin_type < 2 || (adminInfo.admin_type === 2 && adminInfo.action_permissions && adminInfo.action_permissions.includes('3'))"
          :type=" 'primary'" :disabled="selcetRow.user_status != 1"
          :loading="exportBatchLoading" @click="handleOpt(3)">
          撤回用户工资
        </el-button>
        <el-button
          v-if="adminInfo.admin_type < 2 || (adminInfo.admin_type === 2 && adminInfo.action_permissions && adminInfo.action_permissions.includes('3'))"
          :type=" 'primary'" :disabled="selcetRow.team_status != 1"
          :loading="exportBatchLoading" @click="handleOpt(4)">
          撤回团长工资
        </el-button>
      </div>
    </div>
    <div class="layout-container-table">
      <div class="layout-container-table-left">
         <Table ref="category"  v-model:page="page1" v-loading="loading" 
        :showSelection="false"
        :highlightCurrentRow="true"
        :data="tableData1"
        @setCurrent="setCurrent"
        @handleCurrentRowChange="handleCurrentRowChange"
            @getTableData="getTableData1" >
                <el-table-column 
                v-for="(item,index) in columns1" :type="item.type" :key="index"
                :label="item.label"
                :width="item.width"
                :show-overflow-tooltip="true"
                :property="item.property">
                    <template #default="scope" v-if="item.property == 'user_status_name'">
                        <span :class="[scope.row['user_status']>0 &&( scope.row['user_status'] == 2?'cred':'cgree') ]">{{scope.row[item.property]}}</span>
                    </template>
                    <template #default="scope" v-else-if="item.property == 'team_status_name'">
                        <span :class="[scope.row['team_status']>0 &&( scope.row['team_status'] == 2?'cred':'cgree') ]">{{scope.row[item.property]}}</span>
                    </template>
                    <template v-else #default="scope">
                        <el-input
                            v-if="scope.row.showInput" 
                            v-model="scope.row[item.property]" 
                            placeholder="" />
                        <span v-else :class="[item.classes]">{{scope.row[item.property]}}</span>
                    </template>
                </el-table-column>
        </Table>
      </div>
      <div class="layout-container-table-right">
        <Table ref="table" v-model:page="page" v-loading="loading" 
        :data="tableData"
            @getTableData="getTableData">
                <el-table-column 
                v-for="(item,index) in columns2" :type="item.type" :key="index"
                :label="item.label"
                :width="item.width"
                :show-overflow-tooltip="true"
                :property="item.property">
                    <template #default="scope" v-if="item.input">
                        <el-input v-model="scope.row.dict_number" placeholder="" />
                    </template>
                    <template #default="scope" v-else-if="item.copy">
                        <span>{{scope.row[item.property]}} '
                            <el-icon class="cup" v-copy="scope.row[item.property]"  color="#409eff"><DocumentCopy /></el-icon>
                        </span>
                    </template>
                    
                    <template #default="scope" v-else-if="item.image">
                        <el-image
                        v-if="scope.row[item.property]"
                        style="width: 80px; height: 50px; cursor: pointer;"
                        :src="scope.row[item.property]"
                        :preview-src-list="[scope.row[item.property]]"
                        />
                        <div
                        v-else
                        class="no-img"
                        >
                        暂无图片
                        </div>
                    </template>
                    <template #default="scope" v-else-if="item.tooltip">
                        <el-popover
                            placement="bottom"
                            @show="(()=>{getHistoryPeopleLevel(scope.row)})"
                            :disabled="scope.row[item.property] ==''?true:false"
                            trigger="hover">
                            <div slot="content">
                                <template v-if="item.property == 'team_people_level'">
                                    <div v-for="(el, i) in historyPeopleLevelArr" :key="i">
                                        {{el}}
                                    </div>
                                </template>
                                <div v-else-if="item.property == 'status'">
                                    status
                                </div>
                                <template v-else>
                                    {{scope.row[item.property]}}
                                </template>
                                
                            </div>
                            <template #reference>
                                
                                <template v-if="item.property == 'remark' || item.property == 'delivery_address'">
                                    <span v-if="scope.row[item.property] == ''">无</span>
                                    <el-button v-else type="text">查看</el-button>
                                </template>
                                
                                <el-button v-else type="text">{{scope.row[item.property]}}</el-button>
                            </template>
                        </el-popover>
                    </template>
                    <template  #default="scope" v-else>
                        <template v-if="item.property">
                            <el-input
                                v-if="scope.row.showInput" 
                                v-model="scope.row[item.property]" 
                                placeholder="" />
                            <span v-else :class="[item.classes]">{{scope.row[item.property]}}</span>
                        </template>
                    </template>
                </el-table-column>
        </Table>
      </div>
      
    </div>
      <!-- 上传文件弹出框组件 -->
        <BatchImportDialog 
        v-if="uploadObj.visible"
        :visible="uploadObj.visible"
        :title="uploadObj.title"
        :uploadObj="uploadObj"
        @closeUploadDialog="closeUploadDialog"
        @refreshTable="refreshTable"/>
  </div>
</template>

<script lang="ts">
import { defineComponent} from "vue";
import Copy from '@/directive/copy'
  export default defineComponent({
    directives: {
      Copy
    },
  
    setup(props) {
    }
  })
</script>
<script setup lang="ts">
import {  ref, reactive ,nextTick,toRefs,getCurrentInstance  } from "vue";
import { Page } from "@/components/table/type";
import { ElMessage, ElMessageBox ,ElIcon } from "element-plus";
import BatchImportDialog from "@/components/uploadFile/batchImportDialog.vue";
import {
  DocumentCopy
} from '@element-plus/icons-vue'


import Table from "@/components/table/index.vue";
import {
  salaryUserFileQuery,salaryUserQuery,salaryPayOffUserReturn,salaryPayOffTeamUserReturn,
  salaryPayOffUser,salaryPayOffTeamUser,salaryDelete,salaryExpor
} from "@/api/salary.ts";

import { dateFormat, intervalTime, calculateDiffTime } from "@/utils/index.ts";
import { useStore } from "vuex";
import { useRouter, useRoute } from "vue-router";
import { ossPrefixNew } from "@/utils/index.ts";
import { del } from "@/api/table";
const router = useRouter();
const store = useStore();
const adminInfo = reactive(store.state.user.adminInfo);

// 存储搜索用的数据
const query = reactive({
  
});
// 状态 0 未生效 1已完成 2 已领取 3指派中 4返修中 5 闲置中 6 已作废
const statusOptions = ref([
   {
    label: '全部',
    value: -1
  },
  {
    label: '上架',
    value: 1
  },
  {
    label: '下架',
    value: 0
  }
])
const productTypeList = ref([
   {
    label: '全部',
    value: -1
  },
  {
    label: '现金',
    value: 1
  },{
    label: '商品',
    value: 2
  },
])

// 状态change事件
const changeStatus = () => {
  getTableData(true);
}

// 分页参数, 供table使用
const page: Page = reactive({
  index: 1,
  size: 50,
  total: 0,
});

// 分页参数, 供table使用
const page1: Page = reactive({
  index: 1,
  size: 50,
  total: 0,
});


const columns = ref([])
const columns1 = reactive([
    {
        label:'序号',
        property:'Id', 
        width:'55',
    },
    {
        label:'文件名',
        property:'file_title',
    },{
        label:'上传时间',
        property:'created_at',
    },{
        label:'用户支付状态',
        property:'user_status_name',
        status:true,
    },{
        label:'团长支付状态',
        property:'team_status_name',
        status:true,
    }
]);

const columns2= reactive([
    {
        label:'编号',
        property:'Id', 
        width:'55',
    },
    {
        label:'用户ID',
        property:'user_id',
        width:'130px',
    },{
        label:'用户姓名',
        property:'real_name',
    },{
        label:'用户昵称',
        property:'nick_name',
    },{
        label:'用户基础工资',
        property:'base_salary',
        classes:'blue',
    },{
        label:'用户奖励工资',
        property:'incentive_salary',
    },{
        label:'用户总工资',
        property:'sum_salary',
    },{
        label:'用户芝草数',
        property:'balance',
    },{
        label:'所属项目ID',
        property:'project_id',
    },{
        label:'发放备注',
        property:'remarks',
    },{
        label:'是否视为有效人数',
        property:'hyperlink',
    },{
        label:'团长奖励是否发放',
        property:'is_team_salary_name',
    },{
        label:'团长发放备注',
        property:'team_remarks',
    },{
        label:'团长ID',
        property:'team_user_id',
    },{
        label:'团长姓名',
        property:'team_real_name',
    },{
        label:'团长昵称',
        property:'team_nick_name',
    },{
        label:'团长金额',
        property:'team_salary',
    },{
        label:'团长芝草',
        property:'team_balance',
    },{
        label:'团队编号',
        property:'team_number',
    },{
        label:'团队等级',
        property:'level',
    },{
        label:'团长邮箱号',
        property:'team_email',
    },{
        label:'用户发放时间',
        property:'user_grant_time',
        width:160,
    },{
        label:'团长发放时间',
        property:'team_grant_time',
        width:160,
    },{
        label:'用户撤回时间',
        property:'user_withdraw_time',
        width:160,
    },{
        label:'团长撤回时间',
        property:'team_withdraw_time',
        width:160,
    },
]);
const loading = ref(false);
const loading1 = ref(false);
const tableData = ref([]);
const tableData1 = ref([]);

const getParams = ()=>{
    let obj = {
        page: page.index,
        page_size: page.size,
        file_id: selcetRow.value && selcetRow.value.Id,
        ...query
    }
    return obj
}


const category = ref();
const selcetRow = ref({})
// 获取表格数据
const setCurrent = (row:Object) => {
    nextTick(()=>{
        selcetRow.value = row;
        category.value.$refs.systemTable.setCurrentRow(row)
    })
}
// 单选数据
const handleCurrentRowChange = (row:Object) => {
    selcetRow.value = row || {};
    getTableData(true);
}
const getTableData1 = (init: Boolean) => {
  debugger
  loading1.value = true;
  let selcetRows = JSON.parse(JSON.stringify(selcetRow.value) )
  tableData1.value = []
  if (init) {
    page1.page = 1;
  }
  let params = {
    page:page1.index,
    page_size:page1.size
  }
//   salaryUserFileQuery,salaryUserQuery
  salaryUserFileQuery(params)
    .then((res: any) => {
      let data = res.data.list;
      data.forEach((d: any) => {
        d.loading = false;
        d.user_status_name = d.user_status == 0?'用户未支付':d.user_status == 2?'用户已撤回':'用户已支付'
        d.team_status_name = d.team_status == 0?'团长未支付':d.team_status == 2?'团长已撤回':'团长已支付'
        d.created_at = d.created_at?dateFormat(d.created_at):''
      });
      tableData1.value = data;
      setTimeout(() => {
        setCurrent(tableData1.value[0] || {})
      }, 100);
      // handleCurrentRowChange(tableData1.value[0])
      page1.total = Number(res.data.count);
    })
    .catch(() => {
      tableData1.value = [];
      page1.index = 1;
      page1.total = 0;
    })
    .finally(() => {
      loading.value = false;
    });
};
getTableData1(true)

// params <init> Boolean ，默认为false，用于判断是否需要初始化分页
const getTableData = (init: Boolean) => {
  loading.value = true;
  if (init) {
    page.index = 1;
  }
  tableData.value = [];
  let params = getParams()
//   salaryUserFileQuery,salaryUserQuery
  salaryUserQuery(params)
    .then((res: any) => {
      let data = res.data.list;
      data.forEach((d: any) => {
        d.loading = false;
        d.user_grant_time = d.user_grant_time == '0001-01-01T00:00:00Z'?'-': dateFormat(d.user_grant_time) 
        d.team_grant_time = d.team_grant_time == '0001-01-01T00:00:00Z'?'-': dateFormat(d.team_grant_time) 
        d.user_withdraw_time = d.user_withdraw_time == '0001-01-01T00:00:00Z'?'-': dateFormat(d.user_withdraw_time) 
        d.team_withdraw_time = d.team_withdraw_time == '0001-01-01T00:00:00Z'?'-': dateFormat(d.team_withdraw_time) 
        d.is_team_salary_name = d.is_team_salary == 1?'是':'否'
    //     {
    //     label:'用户发放时间',
    //     property:'user_grant_time',
    // },{
    //     label:'团长发放时间',
    //     property:'team_grant_time',
    // },{
    //     label:'用户撤回时间',
    //     property:'user_withdraw_time',
    // },{
    //     label:'团长撤回时间',
    //     property:'team_withdraw_time',
    // },
      });
      tableData.value = data;
      page.total = Number(res.data.count);
    })
    .catch(() => {
      tableData.value = [];
      page.index = 1;
      page.total = 0;
    })
    .finally(() => {
      loading.value = false;
    });
};
const historyPeopleLevelArr = ref([]);
const getHistoryPeopleLevel = (row:any)=>{
    if(row.property == ''){
        historyPeopleLevel({id:row.Id}).then(res => {
            if(res.code == 200){
                historyPeopleLevelArr.value =res.data.list 
            }else{
                ElMessage.success(res.message);
            }
        })
    }
    
}
// 操作
const handleOpt = (type: Number) => {
  ElMessageBox.confirm(`是否确认当前操作?`, "", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "success",
  })
    .then(() => {
     exportBatchLoading.value = true;
      let par = {
        file_id:selcetRow.value.Id,
      }
     if(type == 3){// 撤回用户工资
        setsalaryPayOffUserReturn(par,{user_status:2,user_status_name:'用户已撤回'})
      }else if(type == 4){// 撤回团长工资
        setsalaryPayOffTeamUserReturn(par,{team_status:2,team_status_name:'团长已撤回'})
      }else if(type == 1){//发放用户工资
        setsalaryPayOffUser(par,{user_status:1,user_status_name:'用户已支付'})
      }else if(type == 2){//发放团长工资
        setsalaryPayOffTeamUser(par,{team_status:1,team_status_name:'团长已支付'})
      }else if(type == 0){//删除数据
        par.id = par.file_id;
        delete  par.file_id; 
        setsalayrDelete(par)
      }
    })
    .catch(() => { });
};

const setsalaryPayOffUser = (par:any,obj:any)=> {//
    salaryPayOffUser(par).then(res => {
        if(res.code == 200){
            let selcetRows = selcetRow.value
            let i = tableData1.value.findIndex((el:any) => {return el.Id == selcetRows.Id }) 
            tableData1.value[i].user_status = obj.user_status
            tableData1.value[i].user_status_name = obj.user_status_name
            setCurrent(tableData1.value[i])
            ElMessage.success('操作成功！');
            getTableData(false)
        }else{
           ElMessage.success(res.message);
        }
      
       exportBatchLoading.value = false;
    }).catch(()=>{
        exportBatchLoading.value = false;
    })
}
const setsalayrDelete = (par:any)=> {//
    salaryDelete(par).then(res => {
        if(res.code == 200){
           selcetRow.value = {}
           getTableData1(false)
           ElMessage.success('操作成功！');
        }else{
           ElMessage.success(res.message);
        }
      
       exportBatchLoading.value = false;
    }).catch(()=>{
        exportBatchLoading.value = false;
    })
}
const setsalaryPayOffTeamUser = (par:any,obj:any)=> {
    salaryPayOffTeamUser(par).then(res => {
        if(res.code == 200){
           let selcetRows = selcetRow.value
            let i = tableData1.value.findIndex((el:any) => {return el.Id == selcetRows.Id }) 
            tableData1.value[i].team_status = obj.team_status
            tableData1.value[i].team_status_name = obj.team_status_name
            setCurrent(tableData1.value[i])
            ElMessage.success('操作成功！');
             getTableData(false)
        }else{
           ElMessage.success(res.message);
        }
       
    exportBatchLoading.value = false;
    }).catch(()=>{
        exportBatchLoading.value = false;
    })
}
const setsalaryPayOffUserReturn = (par:any,obj:any)=> {
  debugger
    salaryPayOffUserReturn(par).then(res => {
        if(res.code == 200){
            let selcetRows = selcetRow.value
            let i = tableData1.value.findIndex((el:any) => {return el.Id == selcetRows.Id }) 
            tableData1.value[i].user_status = obj.user_status
            tableData1.value[i].user_status_name = obj.user_status_name
            setCurrent(tableData1.value[i])
            ElMessage.success('操作成功！');
            getTableData(false)
        }else{
           ElMessage.success(res.message);
        }
   exportBatchLoading.value = false;
    }).catch(()=>{
        exportBatchLoading.value = false;
    })
}
const setsalaryPayOffTeamUserReturn = (par:any,obj:any)=> {
    salaryPayOffTeamUserReturn(par).then(res => {
        if(res.code == 200){
           let selcetRows = selcetRow.value
            let i = tableData1.value.findIndex((el:any) => {return el.Id == selcetRows.Id }) 
            tableData1.value[i].team_status = obj.team_status
            tableData1.value[i].team_status_name = obj.team_status_name
            setCurrent(tableData1.value[i])
            ElMessage.success('操作成功！');
            getTableData(false)
        }else{
           ElMessage.success(res.message);
        }
    exportBatchLoading.value = false;
    }).catch(()=>{
        exportBatchLoading.value = false;
    })
}

const uploadObjImg = reactive({
  accept: ".png, .jpg, .jpeg",
});

const uploadFileFun = (fileInfo: any,row:any,index:any) => {
  let file = fileInfo.file;
  const fileType = [".png", ".jpg", ".jpeg"];
  const type = file.name.substr(file.name.lastIndexOf(".")).toLowerCase();
  // 上传类型限制
  if (!fileType.includes(type)) {
    let type = fileType.join("，");
    ElMessage.error(`温馨提示：只支持${type}格式的文件`);
    return;
  }
  // 上传大小限制
  const sizeLimit = file.size / 1024 / 1024 <= 5;
  if (!sizeLimit) {
    ElMessage.error("文件最大不能超过5MB");
    return;
  }

  let formData = new FormData();
  formData.append("file", file);
  formData.append("adv_id", row.Id);

  let data = {
    data: formData,
  };
  advPath(data).then((res: any) => {
    if (res.code) {
      ElMessage.success(`上传成功`);
      tableData.value.splice(index,1,{...row,adv_path:res.data})
    }
  });
};

// 勾选数据
const selectData = ref([]); // 系统id
const handleSelectionChange = (data: any) => {
  selectData.value = [];
  data.forEach((item: any) => {
    selectData.value.push(item.product_id);
  });
};
// 导出题目答案与表格
const exportBatchLoading = ref(false);
const exportSingleLoading = ref(false);
const exportExcelFun = () => {
  exportBatchLoading.value = true;
  exportExcelPost()
}
// 导出通用函数
const exportExcelPost = () => {
  let data = {
    file_id: selcetRow.value.Id, // array[interger]
  }
  salaryExpor(data).then((res: any) => {
    if (res.code === 200) {
      ElMessage.success('导出成功');
      window.open(res.data);
    }
  }).finally(() => {
    exportBatchLoading.value = false;
    exportSingleLoading.value = false;
  })
}
// 批量导入用户
const uploadObj = reactive({
  fileType: ['.xls', '.xlsx'],
  accept: '.xls, .xlsx', // 文件上传类型
  multiple: false, // 是否支持多选
  visible: false,
  title: '',
  url: '', // 批量导入用户接口地址
  type:'team',
  downloadObj: {
    name: '',
    url: ''
  }
});
const closeUploadDialog = ()=>{
    uploadObj.visible = false
    exportBatchLoading.value = false;
}
const refreshTable = ()=>{
    ElMessage.success("导入成功！")
    exportBatchLoading.value = false;
    closeUploadDialog()
    getTableData1(true)
}

const handleBatchImport = () => {
  exportBatchLoading.value = true;
  let obj1 = {
    title:'上传批量发放用户奖励表',
    url:'批量发放用户奖励'
  } 
  uploadObj.visible = true;
  uploadObj.title =  obj1.title;
  uploadObj.url = '/admin/salary/salary_import';
  uploadObj.downloadObj.name = obj1.url; // excel模板名称
  uploadObj.downloadObj.url = `${ossPrefixNew}${obj1.url}.xlsx`; // excel模板下载地址
}

</script>

<style lang="scss" scoped>
.layout-container-form {
    display: flex;
    justify-content: space-between;
    flex-wrap: nowrap;
    align-items: center;
}

.layout-container-form-search {
  width: 100%;
  display: inline-block !important;
  justify-content: flex-start !important;

  .search-btn {
    margin-right: 10px;
    ;
  }
}

.layout-container-opt {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding: 10px;
  margin-top: 10px;
}
.layout-container-table{
    display: flex;
    justify-content: space-between;

    &-left{
        width: 550px;
        th.el-table_1_column_1 {
            .el-checkbox{
                display: none;
            }
        }
    }
    &-right{
        width: calc(100% - 570px);
    }
}


.split-line {
  margin: 0 8px;
  color: #ccc;
}

.image-slot {
  width: 50px;
  height: 50px;
  background: #fafafa;
  color: #ccc;
  font-size: 12px;
  cursor: pointer;
}
.cup{
    cursor: pointer;
}
.cred{
  color: red;
}
.cgree{
  color: green;
}
.blue{
    color: #027db4;
}
</style>
